<?php
//以下2行随客户公众号不同需更改
$shareUrl='basic_house';
$appIdKey='APPID';
$phpname="/index.php/";
// $rand = rand()*0.139;
$rand = 234;
$share_link = "";
// $js_API_ROOT = '//'.$_SERVER["HTTP_HOST"];
// if ($_SERVER["HTTP_HOST"]=="www.basichouse.aiyonet.com") {
//     $js_API_ROOT='//'."img.basichouse.aiyonet.com";
// }
if ($_SERVER["HTTP_HOST"]=="www.bhgroup-style.com") {
    $js_API_ROOT='//'."img.bhgroup-style.com";
}
else {
    // $js_API_ROOT = '//'.$_SERVER["HTTP_HOST"];
    //test site
    $js_API_ROOT = '//'."img.basichouse.aiyonet.com";
}
// $rand = 1.2;

define('APP_DEBUG',false);
define('THINK_PATH', dirname(dirname(__FILE__)).'/ThinkPHP/');
// 定义应用目录
// define('APP_PATH',dirname(dirname(__FILE__)).'/'.$shareUrl.'/');
define('APP_PATH',dirname(dirname(__FILE__)).'/Application/');
defined('RUNTIME_PATH') or define('RUNTIME_PATH',   APP_PATH.'Runtime/');   // 系统运行时目录
defined('LOG_PATH')     or define('LOG_PATH',       RUNTIME_PATH.'Logs/'); // 应用日志目录
defined('TEMP_PATH')    or define('TEMP_PATH',      RUNTIME_PATH.'Temp/'); // 应用缓存目录
defined('DATA_PATH')    or define('DATA_PATH',      RUNTIME_PATH.'Data/'); // 应用数据目录
defined('CACHE_PATH')   or define('CACHE_PATH',     RUNTIME_PATH.'Cache/'); // 应用模板缓存目录

require(dirname(dirname(__FILE__))."/ThinkPHP/Common/functions_min.php");
$config = require_once '../Application/Common/Conf/config.php';
C($appIdKey, $config[$appIdKey]);
C('APPSECRET', $config['APPSECRET']);
C('third_app_id', $config['third_app_id']);
C('third_app_secret', $config['third_app_secret']);
C('DATA_CACHE_TYPE', 'File');
C('DB_TYPE', $config['DB_TYPE']);
C('DB_HOST', $config['DB_HOST']);
C('DB_USER', $config['DB_USER']);
C('DB_PWD', $config['DB_PWD']);
C('DB_NAME', $config['DB_NAME']);
C('DB_PORT', $config['DB_PORT']);
C('DB_PREFIX', $config['DB_PREFIX']);
/* 数据缓存设置 */
C('DATA_CACHE_TIME', 0);      // 数据缓存有效期 0表示永久缓存
C('DATA_CACHE_COMPRESS',false);   // 数据缓存是否压缩缓存
C('DATA_CACHE_CHECK',false);   // 数据缓存是否校验缓存
C('DATA_CACHE_PREFIX','');     // 缓存前缀
C('DATA_CACHE_TYPE','File');  // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite|Xcache|Apachenote|Eaccelerator
C('DATA_CACHE_PATH',TEMP_PATH);// 缓存路径设置 (仅对File方式缓存有效)
C('DATA_CACHE_KEY','akdfm876th4rtYUakbcc'); // 缓存文件KEY (仅对File方式缓存有效)    
C('DATA_CACHE_SUBDIR',false);    // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录)
C('DATA_PATH_LEVEL',1);        // 子目录缓存级别

require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Exception.class.php");
require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Cache.class.php");
require(dirname(dirname(__FILE__))."/Application/Home/ORG/WeixinSDK.class.php");
require(dirname(dirname(__FILE__))."/Application/Home/ORG/String.class.php");
require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Cache/Driver/File.class.php");
require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Db/Driver.class.php");
require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Db/Driver/Mysql.class.php");
require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Db.class.php");
require(dirname(dirname(__FILE__))."/ThinkPHP/Library/Think/Model.class.php");
require(dirname(dirname(__FILE__))."/Application/Home/Model/AuthorizationInfoModel.class.php");
require(dirname(dirname(__FILE__))."/Application/Home/Model/ComponentVerifyTicketModel.class.php");
try {
        $signPackage = array();
        $signPackage['appId'] = 'local';
        $signPackage['timestamp'] = 1;
        $signPackage['nonceStr'] = 2;
        $signPackage['signature'] = 3;
        //获得当前地址栏完整地址（包括?后参数）
        $cur_url=$_SERVER["HTTP_HOST"]."/".$shareUrl.$phpname;
        $cur_url='http://' .$cur_url;
        $share_link=$cur_url;
        if($_SERVER["QUERY_STRING"]){
            $cur_url=$cur_url."?".$_SERVER["QUERY_STRING"];
        }
        //如果wx_debug参数不存在，则需要走微信网页授权或自定义分享流程
        if(!array_key_exists('wx_debug', $config)){
            $sdk = new \Home\ORG\WeixinSDK();
            //是否需要网页授权
            $need_weixin_authorize =$config['need_weixin_authorize'];
            if($need_weixin_authorize){
                //判断用户是否已通过微信授权
                $auth_key=$config['weixin_session_key'];
                session_start();
                $cuser=array();
                if(array_key_exists($auth_key,$_SESSION)){
                    $cuser=$_SESSION[$auth_key];
                }
                if(!array_key_exists('openid',$cuser)){
                    //用户未微信网页授权登录
                    //取得回跳url
                    $need_login_url=$config['login_url']."?ret_url=".urlencode($cur_url);
                    header('location:' . $need_login_url);
                    exit;
                }
                else if (stripos($cur_url,'andgoto=')>0){
                    //用户虽已登录，但#未转换，则只能转换成#做一次跳转
                    $cur_url=str_replace('andgoto=', '#', $cur_url);
                    header('location:' . $cur_url);
                    exit;
                }
                // $cuser['subscribe'] = $sdk->get_subscribe($cuser['openid']);
                // $new_s = $cuser;
                // $_SESSION[$auth_key] = $new_s;
                // $subscribe = $cuser['subscribe'];
                // $urnd=$cuser['openid'];
                $urnd=$cuser['token'];
            }
            $s = new \Home\ORG\String();
            $arr = array();
            $arr['appId'] = C('APPID');
            $arr['timestamp'] = time();
            $jsapi_ticket = $sdk->getJs_ticket();
            $arr['nonceStr'] = $s->randString();
            $str = "jsapi_ticket=" . $jsapi_ticket . "&noncestr=" . $arr['nonceStr'] . "&timestamp=" . $arr['timestamp'] . "&url=" . $cur_url;
            $arr['str'] = $str;
            $arr['signature'] = sha1($str);
            $arr['cur_url'] = $cur_url;
            $arr['ticket'] = $jsapi_ticket;
            $signPackage = $arr;
        }
        else {
            $cuser=array('id'=>2,'nickname'=>'测试假微信用户','token'=>'test');
            $urnd=$cuser['token'];
        }
        $wx_share_act=false;
        $wx_share_query=false;
        if(array_key_exists("wx_share_act", $_GET)){
            //商品详情页分享
            if($_GET['wx_share_act']=='share'){
                // $wx_share_act=$_GET['wx_share_act'];
                // $wx_share_query=sprintf("{num:%d}",$_GET['num']);
                header('location:' . $share_link."#/share?num=".$_GET['num']."&name=".$_GET['name']);
                exit;
            }
            
        }
    } catch (Exception $e) {
        // console.log('获得自定义分享参数失败:'.$e->getMessage());
        // print $e->getMessage();       
    }
?>

<!DOCTYPE html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1,user-scalable=0">
<title>BASIC HOUSE</title>
<link href=/basic_house/dist/static/css/app.css?v=<?php echo $rand?> rel=stylesheet>
</head>
<body>
    <div id="app"></div>
     <img id="wx_img" src=""  style="position: absolute;z-index: -1;top:0px;opacity:0;display: none">
     <img id="wx_img2" src=""  style="position: absolute;z-index: -1;top:0px;opacity:0;display: none">
    <script>
        //if (window.location.href.indexOf("from")>-1) {
        //    var a=location.href;
        //    a=a.substring(0,a.indexOf("?"))+a.substring(a.indexOf("#"),a.length);
        //    window.location.href=a;
        //}
        var js_API_ROOT = '<?php echo $js_API_ROOT ?>';
        var urnd='<?php echo $urnd ?>';
        var wx_link=window.location.href;
    </script>
    <script type="text/javascript" src="/basic_house/static/waibujs/jquery.min.js"></script>
    <script type="text/javascript" src="/basic_house/static/waibujs/html2canvas.min.js"></script>
    <!-- <script type="text/javascript" src="/basic_house/static/waibujs/jquery.easing.min.js"></script> -->
    <script type="text/javascript" src="/basic_house/static/waibujs/to.js"></script>
    <script type="text/javascript" src="/basic_house/static/waibujs/transform.js"></script>
    <script type="text/javascript" src="/basic_house/static/waibujs/alloy_finger.js"></script>
    <script src=/basic_house/dist/static/js/manifest.js?v=<?php echo $rand?>></script>
    <script src=/basic_house/dist/static/js/vendor.js?v=<?php echo $rand?>></script>
    <script src=/basic_house/dist/static/js/app.js?v=<?php echo $rand?>></script>
</body>

<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"> </script>
<script>
    var fx_link= '<?php echo $share_link ?>';
    var wx_link2='<?php echo $cur_url ?>'; 
    //全局默认微信分享icon
    var img_src='http://' + '<?php echo $_SERVER['HTTP_HOST']?>/' + '<?php echo $shareUrl?>/';
    var global_wx_imgUrl='http://' + '<?php echo $_SERVER['HTTP_HOST']?>/' + '<?php echo $shareUrl?>/'+'wx_share5.jpg';
    var wx_imgUrl = global_wx_imgUrl;
    //全局微信分享标题
    //商品，造型，日历等几个特殊页面的分享标题
    window.global_wx_title='欢迎大家使用百家好搭配功能';
    var custom_wx_title='查看我分享的百家好';
    var wx_title=global_wx_title;
    var wx_desc='所有的衣服都在你的微信里';
  wx.config({
      debug: false,
      appId: '<?php echo $signPackage["appId"];?>',
      timestamp: '<?php echo $signPackage["timestamp"];?>',
      nonceStr: '<?php echo $signPackage["nonceStr"];?>',
      signature: '<?php echo $signPackage["signature"];?>',
      jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
      ]
  });
    wx.error(function(res) {
        });
        window.wx_init=function wx_init(){
            wx.onMenuShareAppMessage({
                title:wx_title,
                desc: wx_desc, 
                link: wx_link, 
                imgUrl: wx_imgUrl, 
                type: '', 
                dataUrl: '', 
                success: function() {
                    // wx_title=global_wx_title;
                    // wx_imgUrl = global_wx_imgUrl;
                    // wx_init();
                    showalt("分享成功");
                },
                cancel: function() {
                //    wx_title=global_wx_title;
                //    wx_imgUrl = global_wx_imgUrl;
                //    wx_init();
                }
            });
            wx.onMenuShareTimeline({
                title: wx_title,
                link: wx_link,
                imgUrl: wx_imgUrl,
                success: function() {
                //    wx_title=global_wx_title;
                //    wx_imgUrl = global_wx_imgUrl;
                //    wx_init();
                   showalt("分享成功");
                },
                cancel: function() {
                    // wx_title=global_wx_title;
                    // wx_imgUrl = global_wx_imgUrl;
                    // wx_init();
                }
            });

    }
    wx.ready(wx_init);

var wx_chooseImg=function(){
        var imgid="wx_img";
        wx.chooseImage({
        count: 1, 
        sizeType: ['original', 'compressed'], 
        sourceType: ['album', 'camera'], 
        success: function (res) {
            var localIds = res.localIds; 
            $("#"+imgid).attr('src',localIds);
            mattingImg(imgid,"mattingImg")
            var isIphone = navigator.userAgent.indexOf('iPhone') >= 0;
            if (isIphone) {

            }else{
                alert("图片选取成功,正在处理背景");
            }
            $("#ld_div").show();
        }
    });
    }
    var posturl='';
    var mattingImg=function(imgid, url){
        posturl=url;
        if(imgid!=''){
           var aaa=$("#"+imgid).attr('src');
           convertImgToBase64(aaa,postImg,'image/jpeg');
       }
       else {
        postImg('');
       }
    }

    function postImg(base64str){
        // alert("进了");
        // 1次
        $.ajax({
           type: "POST",
           url: js_API_ROOT+"/Api/ApiBHCloset/"+posturl,
           dataType: 'json',
           data: {base64str:base64str,urnd:urnd},
           async: false,
           error:function(){
                $("#ld_div").hide();
               alert("网络不稳定请再试一遍！");
           },
           success: function(data){
            $("#ld_div").hide();
                // alert('接口返回');
                // alert(data.succ);
                // alert(data.datas);
               // var dataObj=eval("("+data+")");
               var dataObj = data;
                    console.log(dataObj.succ)
                    console.log(dataObj.datas)
                    if(dataObj.succ==1){
                        $("#wx_img").attr("src",dataObj.datas);
                        // $("#wx_img").show();
                        var link=window.location.href.replace("modelling","upload_photos")+"?img="+encodeURIComponent(dataObj.datas);
                        // alert(link);
                        window.location=link;
                        // 
                    }
                    else {
                         // 2次
                            $.ajax({
                               type: "POST",
                               url: js_API_ROOT+"/Api/ApiBHCloset/"+posturl,
                               dataType: 'json',
                               data: {base64str:base64str,urnd:urnd},
                               async: false,
                               error:function(){
                                    $("#ld_div").hide();
                                   alert("网络不稳定请再试一遍！");
                               },
                               success: function(data){
                                $("#ld_div").hide();
                                    // alert('接口返回');
                                    // alert(data.succ);
                                    // alert(data.datas);
                                   // var dataObj=eval("("+data+")");
                                   var dataObj = data;
                                        console.log(dataObj.succ)
                                        console.log(dataObj.datas)
                                        if(dataObj.succ==1){
                                            $("#wx_img").attr("src",dataObj.datas);
                                            // $("#wx_img").show();
                                            var link=window.location.href.replace("modelling","upload_photos")+"?img="+encodeURIComponent(dataObj.datas);
                                            // alert(link);
                                            window.location=link;
                                            // 
                                        }
                                        else {
                                            // 3次
                                            $.ajax({
                                                   type: "POST",
                                                   url: js_API_ROOT+"/Api/ApiBHCloset/"+posturl,
                                                   dataType: 'json',
                                                   data: {base64str:base64str,urnd:urnd},
                                                   async: false,
                                                   error:function(){
                                                        $("#ld_div").hide();
                                                       alert("网络不稳定请再试一遍！");
                                                   },
                                                   success: function(data){
                                                    $("#ld_div").hide();
                                                        // alert('接口返回');
                                                        // alert(data.succ);
                                                        // alert(data.datas);
                                                       // var dataObj=eval("("+data+")");
                                                       var dataObj = data;
                                                            console.log(dataObj.succ)
                                                            console.log(dataObj.datas)
                                                            if(dataObj.succ==1){
                                                                $("#wx_img").attr("src",dataObj.datas);
                                                                // $("#wx_img").show();
                                                                var link=window.location.href.replace("modelling","upload_photos")+"?img="+encodeURIComponent(dataObj.datas);
                                                                // alert(link);
                                                                window.location=link;
                                                                // 
                                                            }
                                                            else {
                                                                alert('网络原因暂无法修改图片,请稍后再试');
                                                                alert(dataObj.datas);
                                                            }
                                                   }
                                               });
                                        }
                               }
                           });
                    }
           }
       });
    }
    var hiddenImg;
    imitHiddenImg();
    var canvas = document.createElement('CANVAS'); 
    var ctx = canvas.getContext('2d'); 
    function imitHiddenImg(){
        // hiddenImg = new Image; 
        hiddenImg = document.getElementById("wx_img2");
        hiddenImg.crossOrigin = 'Anonymous'; 
        hiddenImg.onload = function(){ 
            canvas.height = hiddenImg.height; 
            canvas.width = hiddenImg.width; 
            ctx.drawImage(hiddenImg,0,0); 
            var dataURL = canvas.toDataURL( 'image/png'); 
            // var isIphone = navigator.userAgent.indexOf('iPhone') >= 0;
            // if (isIphone) {

            // }else{
            //     alert(dataURL);
            // }
            postImg(dataURL); 
            // Clean up 
            canvas = document.createElement('CANVAS'); 
            ctx = canvas.getContext('2d'); 
        }; 
    }
    function convertImgToBase64(url, callback, outputFormat){ 
        
        hiddenImg.src = url;
        var isIphone = navigator.userAgent.indexOf('iPhone') >= 0;
            // if (isIphone) {

            // }else{
            //     setTimeout(function(){
            //         hiddenImg.onload();
            //     },10000);
            // }
    }
    window.removeBlanks = function (base64,imgWidth, imgHeight) {
        var imageData = base64,
                 data = imageData.data,
               getRBG = function(x, y) {
                          return {
                            red:   data[(imgWidth*y + x) * 4],
                            green: data[(imgWidth*y + x) * 4 + 1],
                            blue:  data[(imgWidth*y + x) * 4 + 2]
                          };
                        },
              isWhite = function (rgb) {
                          return rgb.red == 255 && rgb.green == 255 && rgb.blue == 255;
                        },
                scanY = function (fromTop) {
                          var offset = fromTop ? 1 : -1;

                          // loop through each row
                          for(var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {

                            // loop through each column
                            for(var x = 0; x < imgWidth; x++) {
                                if (!isWhite(getRBG(x, y))) {
                                    return y;                        
                                }      
                            }
                        }
                        return null; // all image is white
                    },
                scanX = function (fromLeft) {
                          var offset = fromLeft? 1 : -1;

                          // loop through each column
                          for(var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {

                            // loop through each row
                            for(var y = 0; y < imgHeight; y++) {
                                if (!isWhite(getRBG(x, y))) {
                                    return x;                        
                                }      
                            }
                        }
                        return null; // all image is white
                    };


            var cropTop = scanY(true),
                cropBottom = scanY(false),
                cropLeft = scanX(true),
                cropRight = scanX(false);
        // cropTop is the last topmost white row. Above this row all is white
        // cropBottom is the last bottommost white row. Below this row all is white
        // cropLeft is the last leftmost white column.
        // cropRight is the last rightmost white column.
    };
    window.showalt=function showalt(e){
        $(".tanchuang").text(e);
        $(".tanchuang").fadeIn(function(){
            setTimeout(function(){
                $(".tanchuang").fadeOut()
            },300)
        })
    }
</script>
